package training.framework.presentation;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import training.framework.business.AbstractEntity;
import training.framework.business.AbstractEntityController;
import training.framework.business.AbstractEntitySearchOptions;

@ManagedBean
@SessionScoped
public abstract class AbstractNewEntity<Identifier, 
										Entity extends AbstractEntity<Identifier>, 
										EntitySearchOptions extends AbstractEntitySearchOptions, 
										EntityPanel extends AbstractEntityPanel<Identifier, Entity>> {
	
	private EntityPanel panel;
	private String savedMessage;
	private String initializeOutCome;
	private boolean entitySaved;
	private Class<EntityPanel> entityPanelClass;
	private Class<Entity> entityClass;
	
	public AbstractNewEntity(Class<Entity> entityClass, Class<EntityPanel> entityPanelClass, String initializeOutCome, String savedMessage) {
		
		if(entityClass == null){
			throw new IllegalArgumentException("entityClass == null");
		}
		
		if(entityPanelClass == null){
			throw new IllegalArgumentException("entityPanelClass == null");
		}
		
		if(initializeOutCome == null){
			throw new IllegalArgumentException("initializeOutCome == null");
		}
		
		if(savedMessage == null){
			throw new IllegalArgumentException("savedMessage == null");
		}
		
		this.entityClass = entityClass;
		this.entityPanelClass = entityPanelClass;
		this.initializeOutCome = initializeOutCome;
		this.savedMessage = savedMessage;
	}
		
	public String initialize() throws InstantiationException, IllegalAccessException {
		Entity entity = entityClass.newInstance();
		panel = entityPanelClass.newInstance();
		panel.setEntity(entity);
		entitySaved = false;
		return initializeOutCome;
	}
	
	public AbstractEntityPanel<Identifier, Entity> getPanel() {
		return panel;
	}

	public boolean getEntitySaved() {
		return entitySaved;
	}		

	public void saveEntity() {
		AbstractEntityController<Identifier, Entity, EntitySearchOptions> controller = getController();
		controller.saveEntity(panel.getEntity());
		this.entitySaved = true;
		
		FacesMessage message = new FacesMessage();
		message.setSummary(savedMessage);
		message.setSeverity(FacesMessage.SEVERITY_INFO);
		FacesContext context = FacesContext.getCurrentInstance();
		context.addMessage(null, message);					
	}
	
	protected abstract AbstractEntityController<Identifier, Entity, EntitySearchOptions> getController();
}